package com.netease.nie.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.netease.nie.base.cache.redis.Redis;
import com.netease.nie.common.CommonService;
import com.netease.nie.constants.CachePrefixConstants;
import com.netease.nie.dao.DrawLotteryPromptDao;
import com.netease.nie.model.DrawLotteryPrompt;

/**
 * 抽奖不中奖提示业务服务接口实现
 * @author gzlibingjie
 */
@Service
public class DrawLotteryPromptServiceImpl extends CommonService implements DrawLotteryPromptService {

	@Resource
	private DrawLotteryPromptDao drawLotteryPromptDao;
	
	@Autowired
	private Redis redis;
	
	private static final String DRAW_LOTTERY_PROMPT_PREFIX = CachePrefixConstants.DrawLotteryPrefix.DRAW_LOTTERY_PROMPT_PREFIX;
	
	/**
	 * 获取指定抽奖活动下的不中奖提示列表
	 * @param activityId 抽奖活动ID
	 * @return 不中奖提示列表
	 */
	@Override
	public List<DrawLotteryPrompt> listByActivityId(Integer activityId) {
		if (activityId == null) {
			return null;
		}
		return queryByActivityId(activityId);
	}

	/**
	 * 随机获取一个不中奖提示
	 * @param activityId 抽奖活动ID
	 * @return 不中奖提示
	 */
	@Override
	public DrawLotteryPrompt randomQueryOne(Integer activityId) {
		if (activityId == null) {
			return null;
		}
		List<DrawLotteryPrompt> drawLotteryPromptList = queryByActivityId(activityId);
		if (drawLotteryPromptList == null || drawLotteryPromptList.isEmpty()) {
			return null;
		}
		int random = (int) Math.floor(Math.random() * drawLotteryPromptList.size());
		return drawLotteryPromptList.get(random);
	}
	
	/**
	 * 获取抽奖活动下的不中奖提示列表
	 * @param activityId 抽奖活动ID
	 * @return 不中奖提示列表
	 */
	private List<DrawLotteryPrompt> queryByActivityId(Integer activityId) {
		String promptKey = DRAW_LOTTERY_PROMPT_PREFIX + activityId;
		List<DrawLotteryPrompt> drawLotteryPromptList = null;
		if (redis.exists(promptKey)) {
			drawLotteryPromptList = redis.lrange(promptKey, 0, -1, DrawLotteryPrompt.class);
		} else {
			drawLotteryPromptList = drawLotteryPromptDao.queryByActivityId(activityId);
			if (drawLotteryPromptList != null && !drawLotteryPromptList.isEmpty()) {
				redis.rpush(promptKey, drawLotteryPromptList);
			}
		}
		return drawLotteryPromptList;
	}

}
